package com.zhu.storesmanager.views;

import java.util.ArrayList;
import java.util.List;

import com.zhu.storesmanager.R;
import com.zhu.storesmanager.models.DataItem;
import com.zhu.storesmanager.utils.DataUtils;
import com.zhu.storesmanager.utils.Log;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

/**
 * 弹框选择界面 
 */
public class ChoiceView extends TextView{
	private static final String SPLIT = DataUtils.SPLIT_ROW;

    private List<DataItem> mDataList = null; //选择数据集
    private String[] mDataArray = null;
    private boolean isMultiChoice = false; //是否为多选框  默认单选
    private ListView mListView = null; //选择列表
    private int mSelectIndex = -1; //单选选中
    private int mLastSelectIndex = -1; //上次单选选中
    private String mMultiSelectIDs = ""; //多选选中集合  以逗号分隔
    private DataChangeListener mDataChangeListener = null; //数据变化监听

	public ChoiceView(Context context) {
		this(context, null);
		// TODO Auto-generated constructor stub
	}

	public ChoiceView(Context context, AttributeSet attrs) {
		this(context, attrs, 0);
		// TODO Auto-generated constructor stub
	}

	public ChoiceView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		// TODO Auto-generated constructor stub
		setOnClickListener(mClickListener);
		TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ChoiceView, defStyle, 0);
		isMultiChoice = a.getBoolean(R.styleable.ChoiceView_multiChoice, false); //单选OR多选
		setSingleLine(true); //单行显示
	}

	/**
	 * 设置选择项所有数据集合
	 * 数据集合
	 */
	public void setChoiceDataList(List<DataItem> list){
		mSelectIndex = -1;
		mLastSelectIndex = -1;
	    mMultiSelectIDs = "";
		mDataList = list;
		if(mDataList != null && mDataList.size() > 0){ //设置选择数组
			mDataArray = new String[mDataList.size()];
			for(int i = 0; i < mDataList.size(); i++){
				mDataArray[i] = mDataList.get(i).mDataName;
			}
		}
		setText(null);
	}

	/**
	 * 设置为多选框
	 */
	public void setMultiChoice(){
		isMultiChoice = true; 
	}

	/**
	 * 点击事件监听
	 */
	private OnClickListener mClickListener = new OnClickListener(){
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Log.d("isMultiChoice="+isMultiChoice);
			if(isMultiChoice){ //多选
				popMultiChoiceDialog();
			}else{//单选
				popSingleChoiceDialog();
			}
		}
	};

	/**
	 * 弹出多选框
	 */
	private void popMultiChoiceDialog(){
		if(mDataArray == null || mDataArray.length == 0){
			return;
		}
		AlertDialog builder = new AlertDialog.Builder(getContext())
        .setTitle(R.string.please_select)
        .setMultiChoiceItems(mDataArray, getMultiSelected(), null)
        .setPositiveButton(R.string.button_ok, new DialogInterface.OnClickListener(){
            @Override
            public void onClick(DialogInterface dialog, int which) { //确定
                String s = "" ;
                mMultiSelectIDs = "";
                int selectCount = 0;
                for (int i = 0; i < mDataArray.length; i++) {
                    if (mListView.getCheckedItemPositions().get(i)) {
                    	s += mListView.getAdapter().getItem(i) + DataUtils.SPLIT_TEXT; //显示文本
                    	selectCount++;
                        mMultiSelectIDs += mDataList.get(i).mDataId + SPLIT; //保存选中记录ID
                    }
                }
                if(selectCount > 0){
                	s = s.substring(0, s.length() - 1);
                }
                ChoiceView.this.setText(s);
                if(mDataChangeListener != null){
                	mDataChangeListener.onDataChange(ChoiceView.this);
                }
            }
        })
        .setNegativeButton(R.string.cancel, null).create();
		mListView = builder.getListView();
        builder.show();
	}

	/**
	 * 单选框
	 */
	private void popSingleChoiceDialog() {
		if(mDataArray == null || mDataArray.length == 0){
			return;
		}
		new AlertDialog.Builder(getContext())
				.setTitle(R.string.please_select)
				.setSingleChoiceItems(mDataArray, mSelectIndex,
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								mSelectIndex = which;
								ChoiceView.this.setText(mDataArray[which]);
								if(mDataChangeListener != null && mLastSelectIndex != which){
				                	mDataChangeListener.onDataChange(ChoiceView.this);
				                }
								mLastSelectIndex = which;
								dialog.dismiss();
							}
						}).show();
	}

	/**
	 * 获取所选选中项
	 */
	private boolean[] getMultiSelected(){
		boolean[] checked = new boolean[mDataList.size()];
		String[] temarray = mMultiSelectIDs.split(SPLIT);
		for(String id : temarray){
			int index = getSelectedIndex(id);
			if(index != -1){
				checked[index] = true; //设置为选中
			}
		}
		temarray = null;
		return checked;
	}

	/**
	 * 获取选中的index
	 * @param id 选中项ID
	 */
	private int getSelectedIndex(String id){
		for(int i = 0; i < mDataList.size(); i++){
			if(mDataList.get(i).mDataId.equals(id)){
				return i;
			}
		}
		return -1;
	}

	/**
	 * 获取选中项数据
	 * @param DataItem 选中项数据
	 */
	private DataItem getSelectedItem(String id){
		for(int i = 0; i < mDataList.size(); i++){
			if(mDataList.get(i).mDataId.equals(id)){
				return mDataList.get(i);
			}
		}
		return null;
	}

	/**
	 * 获取保存数据
	 */
	public String getSaveData(){
		if(isMultiChoice){
			return mMultiSelectIDs;
		}else{
			if(mSelectIndex == -1){
				return null;
			}else{
				return mDataList.get(mSelectIndex).mDataId;
			}
		}
	}

	/**
     * 获取文本显示数据
     */
    public String getSelectedText(){
        return getText().toString();
    }

	/**
	 * 设置选中数据
	 */
	public void setSelectedData(String data){
		if(data != null && data.length() > 0){
			if(isMultiChoice){
				mMultiSelectIDs = data;
				updateMultiText();
			}else{
				mSelectIndex = getSelectedIndex(data);
				if(mSelectIndex != -1){
					setText(mDataArray[mSelectIndex]);
				}
			}
		}
	}

	/**
	 * 更新显示内容
	 */
	private void updateMultiText(){
		String[] temarr = mMultiSelectIDs.split(SPLIT);
		String text = "";
		for(int i = 0; i < temarr.length; i++){
			String id = temarr[i];
			DataItem item = getSelectedItem(id);
			if(item != null){
				if(i == temarr.length - 1){
					text += item.mDataName;
				}else{
					text += item.mDataName + DataUtils.SPLIT_TEXT;
				}
			}
		}
		setText(text);
	}

	/**
	 * 是否有选中的数据
	 */
	public boolean hasSelected(){
		if(isMultiChoice){
			if(mMultiSelectIDs != null && mMultiSelectIDs.trim().length() > 0){
				return true;
			}
		}else{
			if(mSelectIndex != -1){
				return true;
			}
		}
		return false;
	}

	/**
	 * 获取单选选中的DataItem
	 */
	public DataItem getSingleSelectedDataItem(){
		if(mSelectIndex != -1){
			return mDataList.get(mSelectIndex);
		}
		return null;
	}

	/**
	 * 数据变化监听
	 */
	public interface DataChangeListener{
         public void onDataChange(ChoiceView view);
	}

	/**
	 * 清空数据
	 */
	public void clearData(){
		mDataArray = null;
	    mSelectIndex = -1;
	    mLastSelectIndex = -1;
	    mMultiSelectIDs = "";
		if (mDataList != null) {
			mDataList.clear();
			mDataList = null;
		}
		setText("");
	}

	/**
	 * 设置数据变化监听
	 */
	public void setDataChangeListener(DataChangeListener listener){
		mDataChangeListener = listener;
	}
}
